package com.example.courseapp.activity;

import static com.example.courseapp.activity.RecordActivity2.validateBMI;
import static com.example.courseapp.utils.TimeUtils.getSafeDateFormat;
import static com.example.courseapp.utils.TimeUtils.isToday;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.LogUtils;
import com.example.courseapp.R;
import com.example.courseapp.RetrofitHelper;
import com.example.courseapp.bean.ChildDietaryRecords;
import com.example.courseapp.bean.ChildInformation;
import com.example.courseapp.bean.ChildSportRecords;
import com.example.courseapp.bean.FoodInfo;
import com.example.courseapp.bean.NewFoodInfo;
import com.example.courseapp.bean.Report;
import com.example.courseapp.bean.SportInfo;
import com.example.courseapp.constant.TimeConstants;
import com.example.courseapp.net.CourseService;
import com.example.courseapp.utils.BigDecimalUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class ReportActivity extends AppCompatActivity {

    Button back, save;
    TextView content;
    TextView content2;

    CourseService service;

    HashMap<String, FoodInfo> map = new HashMap<>();
    HashMap<String, SportInfo> map1 = new HashMap<>();

    ChildInformation childInformation;

    Report report = new Report();

    Report getReport;
    Integer childID;
    Handler handler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            if (childInformation == null) return;

            StringBuffer foodStr = new StringBuffer();
            AtomicInteger foodEnergy = new AtomicInteger();
            AtomicInteger sportEnergy = new AtomicInteger();
            foodStr.append("今日饮食： \n");
            map.forEach((string, foodInfo) -> {
                foodStr.append(foodInfo.getFoodName());
                foodStr.append((100 * foodInfo.number) + "g");

                foodStr.append("\n");
//                foodEnergy.addAndGet(foodInfo.getEnergy() * foodInfo.number);

                foodEnergy.addAndGet(Integer.valueOf(BigDecimalUtils.mul(String.valueOf(foodInfo.getEnergy()), String.valueOf(foodInfo.number), 0)));
            });
            foodStr.append("今日运动: \n");
            map1.forEach((string, sportInfo) -> {

                foodStr.append(sportInfo.getName());
                foodStr.append(BigDecimalUtils.mul(String.valueOf(sportInfo.number), "0.5", 1) + "小时 ");
                foodStr.append(BigDecimalUtils.mul(sportInfo.getEnergy(), String.valueOf(sportInfo.number), 0) + "能量");
                foodStr.append("\n");

                sportEnergy.addAndGet(Integer.valueOf(BigDecimalUtils.mul(sportInfo.getEnergy(), String.valueOf(sportInfo.number), 0)));
            });

            foodStr.append("今日共摄入能量" + foodEnergy + "千卡 \n");

            foodStr.append("今日共消耗能量" + sportEnergy + "千卡").append("\n");


            double point = childInformation.getWeight() * 30 + childInformation.getHeight() * 0.6 - childInformation.getAge() * 7.1 + 250;

            DecimalFormat decimalFormat = new DecimalFormat("#.##");
            String formattedNumber = decimalFormat.format(point);
            foodStr.append("每日所需能量为" + formattedNumber + "千卡");

            content.setText(foodStr);

            report.setContent(String.valueOf(foodStr));

            AtomicReference<Float> rou = new AtomicReference<>(0f);
            map.forEach((s, foodInfo) -> {
                if (s.contains("肉")) {
                    rou.set((float) (foodInfo.getEnergy() * foodInfo.number));
                }
            });
            StringBuffer jianyi = new StringBuffer();

            float value = foodEnergy.get() - sportEnergy.get();

            if (value / point > 1.1f) {
                jianyi.append("摄入能量超过所需能量，应该减少摄入或增强运动");
            } else if (value / point < 0.9f) {
                jianyi.append("摄入能量低于所需能量，应该增加饮食");
            }

            jianyi.append("\n");

            if (rou.get() / foodEnergy.get() > 0.3f) {
                jianyi.append("肉类摄入超过总摄入的30%，应该减少食用肉类");
            } else if (rou.get() / foodEnergy.get() < 0.1f) {
                jianyi.append("肉类摄入低于总摄入的10%，应该增加食用肉类");
            }

            AtomicReference<Float> time = new AtomicReference<>((float) 0);

            map1.forEach((string, sportInfo) -> {
                time.updateAndGet(v -> Float.valueOf(v + sportInfo.number * 0.5f));
            });

            jianyi.append("\n");

            if (time.get() > 1f) {
                jianyi.append("今日运动适量");
            } else if (time.get() > 2f) {
                jianyi.append("今日运动过量，请减少运动");
            } else if (time.get() < 1f) {
                jianyi.append("今日运动量较少，请将强运动");
            }

            StringBuilder pjStr = new StringBuilder();
            pjStr.append("\n评价：" + validateBMI(childInformation.getWeight(), childInformation.getHeight()));

            try {
                if (getReport != null && getReport.getProposal() != null) {
                    pjStr.append("\n" + "建议：" + getReport.getProposal());
                } else {
                    pjStr.append("\n" + "建议：" + jianyi);
                    report.setProposal(jianyi.toString());
                }
                content2.setText(pjStr.toString());
            } catch (Exception e) {
                LogUtils.e("error === " + e);
            }

        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_report);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });
        childID = getIntent().getIntExtra("childID", 0);

        back = findViewById(R.id.back);
        save = findViewById(R.id.save);

        back.setOnClickListener(v -> {
            finish();
        });

        content = findViewById(R.id.content);
        content2 = findViewById(R.id.content2);

        service = RetrofitHelper.getInstance().createService(CourseService.class);

        Integer childID = getIntent().getIntExtra("childID", 0);
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String formattedDateTime = now.format(formatter);
        report.setCreateTime(formattedDateTime);

        service.getDietaryList(childID).enqueue(new Callback<List<ChildDietaryRecords>>() {
            @Override
            public void onResponse(Call<List<ChildDietaryRecords>> call, Response<List<ChildDietaryRecords>> response) {
                List<ChildDietaryRecords> list = response.body();

                LogUtils.i("getDietaryList === " + GsonUtils.toJson(response.body()));

                if (list != null && list.size() > 0) {
                    childInformation = list.get(0).getChildInformation();
                    map.clear();
                    for (ChildDietaryRecords records : list) {

                        boolean isToady = isToday(records.getCreateTime(), getSafeDateFormat("yyyy-MM-dd HH:mm:ss"));

                        if (isToady) {
                            List<FoodInfo> courseList = new Gson().fromJson(records.getFood(), new TypeToken<List<FoodInfo>>() {
                            }.getType());

                            for (int i = 0; i < courseList.size(); i++) {
                                FoodInfo foodInfo = courseList.get(i);
                                foodInfo.number = 0;
                                if (map.containsKey(foodInfo.getFoodName())) {
                                    map.get(foodInfo.getFoodName()).number += 1;
                                } else {
                                    foodInfo.number = 1;
                                    map.put(courseList.get(i).getFoodName(), foodInfo);
                                }
                            }
                        }
                    }
                    handler.sendEmptyMessage(0);
                } else {
                    Toast.makeText(ReportActivity.this, "数据为空", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<List<ChildDietaryRecords>> call, Throwable t) {

            }
        });


        service.getSportList(childID).enqueue(new Callback<List<ChildSportRecords>>() {
            @Override
            public void onResponse(Call<List<ChildSportRecords>> call, Response<List<ChildSportRecords>> response) {
                List<ChildSportRecords> list = response.body();
                LogUtils.i("getSportList === " + GsonUtils.toJson(response.body()));

                if (list != null && list.size() > 0) {
                    for (ChildSportRecords records : list) {
                        boolean isToady = isToday(records.getCreateTime(), getSafeDateFormat("yyyy-MM-dd HH:mm:ss"));
                        if (isToady) {
                            List<SportInfo> courseList = new Gson().fromJson(records.getSport(), new TypeToken<List<SportInfo>>() {
                            }.getType());
                            map1.clear();

                            for (int i = 0; i < courseList.size(); i++) {
                                SportInfo sportInfo = courseList.get(i);
                                sportInfo.number = 0;
                                if (map1.containsKey(sportInfo.getName())) {
                                    map1.get(sportInfo.getName()).number += 1;
                                } else {
                                    sportInfo.number = 1;
                                    map1.put(courseList.get(i).getName(), sportInfo);
                                }
                            }
                        }
                    }
                    handler.sendEmptyMessage(0);
                }
            }

            @Override
            public void onFailure(Call<List<ChildSportRecords>> call, Throwable t) {

            }
        });

        service.getReport(childID).enqueue(new Callback<List<Report>>() {
            @Override
            public void onResponse(Call<List<Report>> call, Response<List<Report>> response) {
                List<Report> list = response.body();
                if (list != null && list.size() > 0) {
                    for (Report report1 : list) {
                        boolean isToady = isToday(report1.getCreateTime(), getSafeDateFormat("yyyy-MM-dd HH:mm:ss"));

                        if (isToady) {
                            getReport = report1;
                        }
                    }
                }
            }

            @Override
            public void onFailure(Call<List<Report>> call, Throwable t) {

            }
        });


        save.setOnClickListener(v -> {
            report.setChildInformation(childInformation);
            service.saveReport(report).enqueue(new Callback<Boolean>() {
                @Override
                public void onResponse(Call<Boolean> call, Response<Boolean> response) {
                    if (Boolean.TRUE.equals(response.body())) {
                        Toast.makeText(ReportActivity.this, "提交成功", Toast.LENGTH_SHORT).show();
                    }
                }

                @Override
                public void onFailure(Call<Boolean> call, Throwable t) {

                }
            });
        });
    }

}